package com.cong.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cong.project.common.ErrorCode;
import com.cong.project.exception.BusinessException;
import com.cong.project.model.entity.MerchantDetail;
import com.cong.project.model.entity.MerchantImages;
import com.cong.project.model.entity.MerchantMessage;
import com.cong.project.model.enums.MerchantStatus;
import com.cong.project.model.request.MerchantAddRequest;
import com.cong.project.model.request.MerchantSearchRequest;
import com.cong.project.model.request.TokenUserRequest;
import com.cong.project.model.vo.MerChantVo;
import com.cong.project.service.MerchantDetailService;
import com.cong.project.service.MerchantImagesService;
import com.cong.project.service.MerchantMessageService;
import com.cong.project.mapper.MerchantMessageMapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86188
* @description 针对表【merchant_message(商户信息表)】的数据库操作Service实现
* @createDate 2022-09-22 10:36:02
*/
@Service
public class MerchantMessageServiceImpl extends MPJBaseServiceImpl<MerchantMessageMapper, MerchantMessage>
    implements MerchantMessageService{

    @Resource
    private MerchantDetailService merchantDetailService;
    @Resource
    private MerchantImagesService merchantImagesService;

    @Override
    public IPage<MerChantVo> getShopList(MerchantSearchRequest merchantSearchRequest) {
        if (merchantSearchRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MPJLambdaWrapper<MerChantVo> lambdaWrapper = new MPJLambdaWrapper<MerChantVo>()
                .select(MerchantMessage::getMerchantName,MerchantMessage::getMerchantStatus,MerchantMessage::getUserId)
                .select(MerchantDetail::getMerchantAddress,MerchantDetail::getMerchantProducts,MerchantDetail::getMerchantId
                ,MerchantDetail::getStarLevel,MerchantDetail::getMerchantAvatar,MerchantDetail::getMerchantIntroduce)
                .leftJoin(MerchantDetail.class,MerchantDetail::getMerchantId,MerchantMessage::getId);

        Long merchantId = merchantSearchRequest.getMerchantId();
        //商户id不为空
        if ((merchantId != null) && (merchantId >= 0)){
            lambdaWrapper.eq(MerchantMessage::getId,merchantId);
        }
        //如果商户创建人id不为空
        Long userId = merchantSearchRequest.getUserId();
        if (userId!=null&&userId>0){
            lambdaWrapper.eq(MerchantMessage::getUserId,userId);
        }

        Integer starLevel = merchantSearchRequest.getStarLevel();
        //星级不为空  且不小于0 大于5
        if (starLevel!=null){
            if ((starLevel > 0) || (starLevel < 5)){
                lambdaWrapper.eq(MerchantDetail::getStarLevel,starLevel);
            }
        }

        String merchantAddress = merchantSearchRequest.getMerchantAddress();
        //商店地址不为空 模糊查询
        if (StringUtils.isNotBlank(merchantAddress)){
            lambdaWrapper.like(MerchantDetail::getMerchantAddress,merchantAddress);
        }
        String merchantProducts = merchantSearchRequest.getMerchantProducts();
        //商店主营产品不为空  模糊查询
        if (StringUtils.isNotBlank(merchantProducts)){
            lambdaWrapper.like(MerchantDetail::getMerchantProducts,merchantProducts);
        }
        MerchantStatus merchantStatus = MerchantStatus.geEnumByValue(merchantSearchRequest.getMerchantStatus());
        // 商店状态不为空 且有状态是在范围内
        if (merchantStatus!=null){
            lambdaWrapper.eq(MerchantMessage::getMerchantStatus,merchantStatus.getValue());
        }
        IPage<MerChantVo> chantVoIPage = this.selectJoinListPage(new Page<>(merchantSearchRequest.getPage(), merchantSearchRequest.getRows()), MerChantVo.class, lambdaWrapper);
        //对状态进行中文的获取，给前端渲染
        List<MerChantVo> collect = chantVoIPage.getRecords().stream().peek(item -> item.setMerchantStatusName(MerchantStatus.geEnumByValue(item.getMerchantStatus()).getText())).collect(Collectors.toList());
        for (MerChantVo merChantVo : collect) {
            List<String> imgList = merchantImagesService.list(new LambdaQueryWrapper<MerchantImages>()
                            .eq(MerchantImages::getMerchantId, merChantVo.getMerchantId())).stream().map(MerchantImages::getImgUrl)
                    .collect(Collectors.toList());
            merChantVo.setImageList(imgList);
        }
        chantVoIPage.setRecords(collect);
        return chantVoIPage;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMerchant(MerchantAddRequest merchantAddRequest, TokenUserRequest tokenUserRequest) {
        //商户详情信息
        MerchantDetail merchantDetail = new MerchantDetail();
        //商户信息
        MerchantMessage merchantMessage = new MerchantMessage();
        //地址信息
        String merchantAddress = merchantAddRequest.getMerchantAddress();
        if (StringUtils.isBlank(merchantAddress)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请填写地址信息");
        }
        //主营产品
        String merchantProducts = merchantAddRequest.getMerchantProducts();
        if (StringUtils.isBlank(merchantProducts)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请填写主营产品");
        }
        //商户头像
        String merchantAvatar = merchantAddRequest.getMerchantAvatar();
        if (StringUtils.isBlank(merchantAvatar)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请填写商户头像");
        }
        //商户名称
        String merchantName = merchantAddRequest.getMerchantName();
        if (StringUtils.isBlank(merchantName)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请填写商户名称");
        }
        //商户主营人
        String merchantMan = merchantAddRequest.getMerchantMan();
        if (StringUtils.isBlank(merchantMan)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请填写商户主营人");
        }
        String merchantManPhone = merchantAddRequest.getMerchantManPhone();
        if (StringUtils.isBlank(merchantManPhone)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请填写商户负责人手机电话");
        }
        BeanUtils.copyProperties(merchantAddRequest,merchantDetail);
        BeanUtils.copyProperties(merchantAddRequest,merchantMessage);
        List<String> merchantProductsImg = merchantAddRequest.getMerchantProductsImg();
        merchantMessage.setUserId(tokenUserRequest.getId());
        boolean save = this.save(merchantMessage);
        if (save){
            //保存商家详细信息
            Long merchantId = merchantMessage.getId();
            merchantDetail.setMerchantId(merchantId);
            boolean saveDetailResult = merchantDetailService.save(merchantDetail);
            if (merchantProductsImg.size()!=0){
                List<MerchantImages> merchantImages = new ArrayList<>();
                for (String img : merchantProductsImg) {
                    MerchantImages merchantImage = new MerchantImages();
                    merchantImage.setMerchantId(merchantId);
                    merchantImage.setImgUrl(img);
                    merchantImages.add(merchantImage);
                }
                //批量保存商家的宣传图片
                return merchantImagesService.saveBatch(merchantImages);
            }
            return saveDetailResult;

        }
        return false;
    }

    @Override
    public MerChantVo getMerchantDetail(Long merchantId) {
        if (merchantId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MPJLambdaWrapper<MerChantVo> lambdaWrapper = new MPJLambdaWrapper<MerChantVo>()
                .select(MerchantMessage::getMerchantName,MerchantMessage::getMerchantStatus,MerchantMessage::getUserId)
                .select(MerchantDetail::getMerchantAddress,MerchantDetail::getMerchantProducts,MerchantDetail::getMerchantId
                        ,MerchantDetail::getStarLevel,MerchantDetail::getMerchantAvatar,MerchantDetail::getMerchantIntroduce)
                .leftJoin(MerchantDetail.class,MerchantDetail::getMerchantId,MerchantMessage::getId);

        //商户id不为空
        if ((merchantId != null) && (merchantId >= 0)){
            lambdaWrapper.eq(MerchantMessage::getId,merchantId);
        }

        MerChantVo merChantVo = this.selectJoinOne( MerChantVo.class, lambdaWrapper);
        //对状态进行中文的获取，给前端渲染
        if (merChantVo!=null){
            merChantVo.setMerchantStatusName(MerchantStatus.geEnumByValue(merChantVo.getMerchantStatus()).getText());
            List<String> imgList = merchantImagesService.list(new LambdaQueryWrapper<MerchantImages>()
                            .eq(MerchantImages::getMerchantId, merChantVo.getMerchantId())).stream().map(MerchantImages::getImgUrl)
                    .collect(Collectors.toList());
            merChantVo.setImageList(imgList);
        }


        return merChantVo;
    }
}




